<?php
class EditItemForm extends Form{
	var $max_image_page=1,$images_per_page=9,$no_image='style/images/no-images-69x53.jpg';
	private $item=false,$images=false,$images_=false, $item_images=array(),$img_url='',$jsImages = array(),$browser_is_ie = 0;
	
	function __construct()
	{
		Form::Form('PostItemForm');
		
		$this->item = DB::select("item","id=" . (int)(Url::get('id',0)));//$this->item = Item::get_item(intval(Url::get('id',0)));
		
		 
		if(!$this->item || !User::have_permit(ADMIN_ITEM))
		{
			if(Url::get('ref'))
				Url::redirect('manage_item');
			else
				Url::redirect('home');
		}
		
		// Nếu ko fải là admin
		if(!User::have_permit(ADMIN_ITEM)){
			if($this->item['user_id']!=User::id() || $this->item['status']==4){ // neu khong phai chu topic
				Url::redirect('item_detail',array('id'=>$this->item['id'],'ebname'=>AZLib::safe_title($this->item['name'])));
			}
		}
		
		CGlobal::$website_title='Sửa sản phẩm';
		
		$this->link_css('style/ItemDetail.css');
		$this->link_css('style/postItem.css');
		$this->link_css('style/gallery.css');
		
		//$this->link_js('javascript/jquery/jquery-1.3.2.js');
		$this->link_js('javascript/jquery/jquery.livequery.js');
		$this->link_js('javascript/jquery/jquery.jcache.js');
		$this->link_js('javascript/jquery/jquery.form.js');
		$this->link_js('javascript/jquery/jquery.ui.js');
		$this->link_js('javascript/jquery/ui.draggable.js');
		$this->link_js('javascript/jquery/ui.droppable.js');
		$this->link_js('javascript/count_character.js');
		
		// For checking flash version of browser
		$this->link_js('javascript/AC_RunActiveContent.js');
		
		// For ajax upload when use IE or other browser has no flash
		$this->link_js('javascript/si.files.js');
		$this->link_js('javascript/ajaxfileupload.js');
		
		// For flash upload
		$this->link_js('javascript/swfupload/swfupload.js');
		$this->link_js('javascript/swfupload/js/swfupload.swfobject.js');
		$this->link_js('javascript/swfupload/js/swfupload.queue.js');
		$this->link_js('javascript/swfupload/js/fileprogress.js');
		$this->link_js('javascript/post_item_handlers.js');
		$this->link_js('javascript/jquery/jquer y.event.drag-1.0.js');
		$this->link_js('javascript/post_item.js');
		if((int)ini_get("memory_limit")<64){@ini_set("memory_limit","64M");}
		
		//$this->no_image			 =AZLib::getImageSrc('',70,70);
		$this->no_image = STATIC_URL.'style/images/no-images-69x53.jpg';
		
		//$re = DB::query('SELECT * FROM item_image WHERE item_id = '.$this->item['id'].' AND user_id = '.$this->item['user_id'].' ORDER BY position');
		$re = DB::query('SELECT * FROM item_image WHERE item_id = '.$this->item['id'].' ORDER BY position');
		$this->images 		= array();
		$position_images 	= array();
		
		if($re){
			while($img=mysql_fetch_assoc($re)){
				if($img['user_id'] == $this->item['user_id']){
					$img['title']=str_replace(array('"'),array('&quot;'),stripslashes($img['title']));
					$this->images[$img['id']]=$img;
					
					if(!$img['user_id'] || !$img['user_name'] || !$img['time']){//Nếu ảnh cũ chưa được cập nhật một số thông tin
						$img['user_id']		=$this->item['user_id'];
						$img['user_name']	=$this->item['user_name'];
						$img['time']		=$this->item['created_time'];
						
						DB::update('item_image',$img,'id='.$img['id']);
					}
					
					$img['title']=str_replace(array('"'),array('&quot;'),stripslashes($img['title']));
					//$this->jsImages[$img['position']]['w180']= CGlobal::$img_server[$img['img_server']] . 'thumb_w/180/' . $img['img_url'];
					$this->jsImages[$img['position']]['id']= $img['id'];
					$this->jsImages[$img['position']]['img_server']= $img['img_server'];
					$this->jsImages[$img['position']]['img_url'] = $img['img_url'];
					$position_images[$img['position']]=$img;
					$this->images[$img['id']]=$img;
				}
			}
		}

		$i=1;
		if($this->images)
		foreach ($this->images as $image){
			$i=	$image['position'];
			$image['title']=str_replace(array('"'),array('&quot;'),stripslashes($image['title']));
			$this->images_[$i]=$image;
		}
		
		$index=1;
		for($i=1;$i<=$this->max_image_page;$i++){//trang ảnh
			$this->item_images[$i]=array();

			for($n=1; $n<=$this->images_per_page;$n++){//số ảnh trên trang
				$this->item_images[$i][$n]['stt']=$index;
				
				if(isset($_POST['img_new'][$index]) && $_POST['img_new'][$index]){					
					
					$this->jsImages[$index]['w180'] = 'thumb_w/180/';
					$this->jsImages[$index]['img_server'] = $_POST['i_server'][$index];
					$this->jsImages[$index]['img_url'] = $_POST['i_url'][$index];
					//$this->jsImages[$index]['server_address'] = CGlobal::$img_server[$_POST['i_server'][$index]];
					$this->jsImages[$index]['image_url'] = AZLib::getImageThumb($_POST['i_url'][$index],80,80,0,$_POST['i_server'][$index]);
					
					$this->item_images[$i][$n]['id']		='0';
					$this->item_images[$i][$n]['img_server']	=$_POST['i_server'][$index];
					$this->item_images[$i][$n]['i_url'] = 	$_POST['i_url'][$index];
					$this->item_images[$i][$n]['image_url']		=AZLib::getImageThumb($_POST['i_url'][$index],80,80,0,$_POST['i_server'][$index]);
					$this->item_images[$i][$n]['title']		=$_POST['image_title'][$index];
					$this->item_images[$i][$n]['img_new_id']	=$_POST['img_new'][$index];
					$this->item_images[$i][$n]['have_img']		=1;
					
					if(isset($position_images[$index]))
						$this->item_images[$i][$n]['img_del_id']=$position_images[$index]['id'];
					else
						$this->item_images[$i][$n]['img_del_id']=0;
				}
				elseif(isset($position_images[$index])){					
					$this->item_images[$i][$n]['id']		=$position_images[$index]['id'];
					$this->item_images[$i][$n]['img_server']	=$position_images[$index]['img_server'];
					$this->item_images[$i][$n]['i_url'] = 	$position_images[$index]['img_url'];
					$this->item_images[$i][$n]['image_url']		=AZLib::getImageThumb($position_images[$index]['img_url'],80,80,0,$position_images[$index]['img_server']);
					$this->item_images[$i][$n]['title']		=$position_images[$index]['title'];
					$this->item_images[$i][$n]['img_new_id']	=0;
					$this->item_images[$i][$n]['have_img']		=1;
					$this->item_images[$i][$n]['img_del_id']	=0;
				}
				else{
					$this->item_images[$i][$n]['img_server']	=0;
					$this->item_images[$i][$n]['image_url']		=$this->no_image;
					$this->item_images[$i][$n]['i_url'] = 	'';
					$this->item_images[$i][$n]['title']		='Ghi chú ảnh';
					$this->item_images[$i][$n]['id']		='';
					$this->item_images[$i][$n]['img_new_id']	=0;
					$this->item_images[$i][$n]['have_img']		=0;
					$this->item_images[$i][$n]['img_del_id']	=0;
				}
				
				$index++;
			}
		}
		
		
		AZLib::getFilters();
	}
	
	function draw()
	{
		global $display;
		
		$this->item['price'] = AZLib::convertCurrency($this->item['price'],			$this->item['currency_id']);								
		$this->item['price_out'] = AZLib::convertCurrency($this->item['price_out'],	$this->item['currency_id']);				
		$this->item['currency_id'] = 1;
		//For ajax_upload form
		$display->add('url_gallery',WEB_ROOT.AZRewrite::formatUrl('?page=gallery&is_popup=1&user_id='.$this->item['user_id']));
		////$display->add('no_img_upload',AZLib::getImageSrc('',100,100));
		$display->add('browser_is_ie',	$this->browser_is_ie);
		$display->add('no_img_upload',$this->no_image);
		$display->add('user_id',		User::id());
		$display->add('item_user_id',	$this->item['user_id']);
		$display->add('is_can_edit',	(int)(User::have_permit(ADMIN_ITEM)));
		$display->add('user_name',	$this->item['user_name']);
		
		if(isset($_POST["avatar_img_server"]))
		{
			$avatar['img_server'] = $_POST["avatar_img_server"];
			$avatar['img_url'] = $_POST["avatar_img_url"];
			$avatar['thumb280_280'] = AZLib::getImageThumb($_POST["avatar_img_url"],280,280,0,$_POST["avatar_img_server"]);
			$avatar['max_path']		= AZLib::getImageThumbMax($_POST["avatar_img_url"],'thumb_max',1,$_POST["avatar_img_server"]);
			$display->add('avatarInfo',$avatar);
			$display->add('avatar',json_encode($avatar));
		}
		elseif($this->item['img_url'])
		{
			$avatar['img_server'] = $this->item['img_server'];
			$avatar['img_url'] = $this->item['img_url'];
			$avatar['thumb280_280'] = AZLib::getImageThumb($this->item['img_url'],280,280,0,$this->item['img_server']);
			$avatar['max_path']		= AZLib::getImageThumbMax($this->item['img_url'],$this->item['name'],1,$this->item['img_server']);
			$display->add('avatarInfo',$avatar);
			$display->add('avatar',json_encode($avatar));
		}
		
		$display->output('ajax_upload');
		//For ajax_upload form	
			
		$this->beginForm(true);
		//$display->add('img_fnkjgk',json_encode($bakjgkj));
		
		$display->add('max_image_page',$this->max_image_page);
		$display->add('images_per_page',$this->images_per_page);
		$display->add('post_item_images',$this->item_images);
		$display->add('jsImages',json_encode($this->jsImages));
		
		if($this->item['level_1_catid'] != $this->item['category_id']) // Chọn danh mục cấp 2
		{
			$first = $this->item['level_1_catid'];
			$second = $this->item['category_id'];
		}
		else
		{
			$first = $this->item['category_id'];
			$second = 0;
		}
		$display->add('first_combo',(int)Url::get('first_combo',$first));
		$display->add('second_combo',(int)Url::get('second_combo',$second));
		///$display->add('category_tree',json_encode(AZLib::getCategoriesTree(0,true)));
		$display->add('category_tree',json_encode(AZLib::getCategoriesTree(true)));
		$display->add('currency_tree',json_encode(CGlobal::$currency));
		
		$display->add('az_filters',json_encode(CGlobal::$filters));
		$display->add('item_filters',$this->item['filter_ids']);
		
		$display->add('image_path','http://'.IMAGE_PATH);
		$display->add('img_cur_server',IMAGE_SERVER_NO);
		$display->add('img_server',json_encode(CGlobal::$img_server));
		
		$display->add('multi_upload',User::have_permit(ADMIN_ITEM));
		$display->add('no_img',	$this->no_image);
		$display->add('post_img', $display->output('post_img',true));
		
		$display->add('currency_id_option',	AZLib::getOption(CGlobal::$currency,Url::get('currency_id',$this->item['currency_id'])));
		
		$display->add('msg',			 $this->showFormErrorMessages(1));
		$display->add('name',			 stripslashes(Url::get('name',$this->item['name'])));
		$display->add('sku',			 Url::get('sku',$this->item['sku']));
		$display->add('offer',			 stripslashes(Url::get('offer',$this->item['offer'])));
		
		if(isset(CGlobal::$allCategories[$this->item['category_id']])){
			$item_href = WEB_DIR.CGlobal::$allCategories[$this->item['category_id']]['nice_name']."/p{$this->item['id']}/".AZLib::safe_title($this->item['name']).".html";
		}
		else{	
			$item_href = WEB_DIR."p{$this->item['id']}/".AZLib::safe_title($this->item['name']).".html";
		}
		
		$display->add('item_href',		 $item_href);
		
		$display->add('name_length',120-mb_strlen(AZLib::stripUnicode(Url::get('name',$this->item['name'])),"UTF-8"));
		$display->add('brief',stripslashes(Url::get('brief',$this->item['brief'])));
		$display->add('item_description',stripslashes(Url::get('item_description',$this->item['description'])));
		$display->add('mode',"CẬP NHẬT");				
				
		$display->add('price',number_format(Url::get('price',$this->item['price']),0,',','.'));				
		$display->add('price_out',	 number_format(Url::get('price_out',$this->item['price_out']),0,',','.'));
		
		
		$display->add('quantity',	number_format(Url::cdouble(Url::get('quantity',$this->item['quantity'])),0,',','.'));
		$display->add('item_order',	(int)Url::get('item_order',$this->item['item_order']));
		$display->add('made_in',	Url::get('made_in',$this->item['made_in']));
		$display->add('warranty',	Url::get('warranty',$this->item['warranty']));
		
		
		$display->output('post_sale');
		
		$this->endForm();
	}
	
	function on_submit()
	{
		AZLib::getCats();
		$sku   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('sku')));
		
		###############################################################################################
		$name   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('name')));
		
		mb_internal_encoding("UTF-8");
		$name 		= mb_strtoupper(mb_substr($name,0,1)).mb_substr($name,1);
		###############################################################################################
		
		###############################################################################################
		
		$offer   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('offer')));
		
		mb_internal_encoding("UTF-8");
		$offer 		= mb_strtoupper(mb_substr($offer,0,1)).mb_substr($offer,1);
		###############################################################################################
		
		###############################################################################################
		
		$list_brief   	= AZLib::trimSpace(str_replace("\n"," ",Url::get('list_brief')));
		
		mb_internal_encoding("UTF-8");
		$list_brief 		= mb_strtoupper(mb_substr($list_brief,0,1)).mb_substr($list_brief,1);
		###############################################################################################
		
		
		###############################################################################################
		
		//$item_description 	= AZLib::getParam('item_description');
		$item_description 	= Url::get('item_description');
		$brief 				= Url::get('brief');
		
		if(get_magic_quotes_gpc()){
			$item_description  	= stripslashes($item_description);
			$brief  			= stripslashes($brief);
		}
		
		require_once ROOT_PATH.'includes/htmLawed.php';
		
		$config = array(
			'safe'=>1, // Dangerous elements and attributes thus not allowed
			'elements'=>'*', // All except table-related are OK
			'deny_attribute'=>'class, id' // None of the allowed elements can have these attributes
		);
		
		$spec = 'a = title, href;'; // The 'a' element can have only these attributes

		$item_description = htmLawed($item_description, $config, $spec);
		$item_description = AZLib::clean_value($item_description);

        $brief 				= htmLawed($brief, $config, $spec);
		$brief 				= AZLib::clean_value($brief);
		###############################################################################################
		
		$category_id 		 = 0;
		$level_1_catid = 0;
		
		$first_combo		 = (int)Url::get('first_combo');
		$second_combo		 = (int)Url::get('second_combo');
		$price				 = Url::cdouble(Url::get('price'));			
		$price_out			 = Url::cdouble(Url::get('price_out'));
		$currency_id		 = (int)Url::get('currency_id',1);
		
		$quantity			= Url::cdouble(Url::get('quantity',0));
		
		if($quantity<0){
			$quantity = 0;
		}
		
		$item_order			= (int)Url::get('item_order');
		$made_in			= Url::get('made_in');
		$warranty			= Url::get('warranty');
		
		if(!isset(CGlobal::$currency[$currency_id])){
			$currency_id=1;
		}
		
		$item_category=false;

		if($first_combo && $second_combo)//Nếu chọn danh mục cấp 2
		{
			$category_id 		 = $second_combo;
			$level_1_catid = $first_combo;
			$level_2_catid = $second_combo;
			
			if(isset(CGlobal::$allCategories[$category_id])){ //Kiểm tra sự tồn tai của danh mục
				$item_category=CGlobal::$allCategories[$category_id];
				
				if((isset(CGlobal::$subCategories[$category_id]) && CGlobal::$subCategories[$category_id] && $item_category['parent_id']==0) ||$item_category['parent_id']!=$first_combo){//Nếu danh mục của sản phẩm là danh mục cấp 1 và có danh mục con => chọn lại
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
			}
		}
		elseif($first_combo){//Nếu chọn danh mục cấp 1
			$category_id 			= $first_combo;
			$level_1_catid 	= $first_combo;
			$level_2_catid 	= $first_combo;
			
			if(isset(CGlobal::$allCategories[$category_id])){ //Kiểm tra sự tồn tai của danh mục
				$item_category=CGlobal::$allCategories[$category_id];
				
				if(isset(CGlobal::$subCategories[$category_id]) && CGlobal::$subCategories[$category_id] && $item_category['parent_id']==0){//Nếu danh mục có danh mục con => Chọn lại!
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
				elseif($item_category['parent_id']!=0){//Nếu không fải là danh mục cấp 1
					$this->setFormError('category_id','Hãy chọn lại <b>Chủng loại</b> cho sản phẩm!');
				}
			}
		}
		
		if(!$item_category){
			$this->setFormError('category_id','Bạn chưa chọn <b>Danh mục</b> cho sản phẩm!');
		}
		
		/*if($price<=0)
		{
			$this->setFormError('price','Với tin rao bán bạn phải nhập <b>Giá</b>');	
		}
		else*/
		if($price > 0)
		{
			if($currency_id==1){
				$this->checkFormInput("Giá bán",'price',$price,'double',false,'',1,50000000000);
			}
			else{
				$this->checkFormInput("Giá bán",'price',$price,'double',false,'',1,1000000);
			}
		}
						
		if($price_out!='' && $price_out!='0'){
			if($currency_id==1){
				$this->checkFormInput("Giá thị trường",'price_out',$price_out,'double',false,'',1,50000000000);
			}
			else{
				$this->checkFormInput("Giá thị trường",'price_out',$price_out,'double',false,'',1,1000000);
			}
		}
		
		$this->checkFormInput('Tên sản phẩm','name',$name,'str',true,'',5,120);
			
		$this->checkFormInput('Mô tả vắn tắt','brief',$brief,'str',false,'',15,500000);
		$this->checkFormInput('Mô tả sản phẩm','item_description',$item_description,'str',true,'',15,500000);
				
		//Check kiểm duyệt
		$status = 1;//Cho hiển thị
		$user_item = User::getUser($this->item['user_id']);				
		
		$status = $this->item['status'];//Giữ nguyên giá trị
		
		$have_image_up = false;
		
		foreach($this->item_images as $page=>$page_images){//trang
			foreach ($page_images as $image){
				if($image['img_new_id']||$image['id']){
					$have_image_up = true;
					break;
				}	
			}
		}
		
		$form_img_server 	= Url::get('avatar_img_server',0);
		$this->img_url 		= Url::get('avatar_img_url','');
		
		if(!$this->errNum){
			$id 	= $this->item['id'];
			
			$item_array = array(
								'category_id'			=>$category_id,
								'level_1_catid'			=>$level_1_catid,
								'level_2_catid'			=>$level_2_catid,
								'currency_id'			=>$currency_id,
								'price'					=>$price,
								'price_out'				=>$price_out,
								'sku'					=>$sku,
								'name'					=>$name,
								'offer'					=>$offer,
								'list_brief'			=>$list_brief,
								'brief'					=>$brief,
								'description'			=>$item_description,								
								'status'				=>$status,
								'quantity'				=>$quantity,
								'item_order'			=>$item_order,
								'made_in'				=>$made_in,
								'warranty'				=>$warranty,
								'modify_time'			=>TIME_NOW,
								'modify_user_name'		=>User::user_name(),
								'have_image'			=>(int)(bool)$this->img_url,
								'img_server'			=>	$form_img_server,
								'img_url'				=>$this->img_url,
								);
			
			/*DB::update('item',$item_array,'id='.$id);

			if(MEMCACHE_ON){
				AZMemcache::do_remove("item:$id");
			}*/
						
			$image_err				=false;
			//$img_url				='';
			$item_images			=array();
			$item_check_images		=array();
			$item_insert_temp_images=array();
			$item_insert_images		=array();
			$item_update_images		=array();
			$item_delete_ids		='';
			$unused_ids				='';
			$img_ids='';
			$item_have_image		= 0;
			//$pos=0;
			
			foreach($this->item_images as $page=>$page_images){//10 trang
				foreach ($page_images as $image){
					
					if($image['img_new_id']){//nếu chọn hoặc thay ảnh mới
						$item_have_image =1;
						$img=array();
						$title=($image['title'] && $image['title']!='Ghi chú ảnh')?$image['title']:'';
						$title=str_replace(array('"'),array('&quot;'),stripslashes($title));
						$title=($title && !AZLib::checkBadWord($title))?$title:'';
						
						if(isset($this->images[$image['img_new_id']])){//Nếu chọn mới hoặc thay 1 ảnh đã có
							if($this->images[$image['img_new_id']]['position']==$image['stt']){//lấy lại chính ảnh cũ
								if($title!=$this->images[$image['img_new_id']]['title']){//Nếu Tên sản phẩm ảnh thay đổi thì cập nhật Tên sản phẩm cho ảnh!
									$this->images[$image['img_new_id']]['title']=addslashes($title);
									$item_update_images[$image['img_new_id']]=$this->images[$image['img_new_id']];
								}
							}
							else{//Nếu ảnh được chọn lại ở vị trí khác
								$img['title']			=addslashes($title);
								$img['item_id']			=$id;
								$img['img_server']		=$this->images[$image['img_new_id']]['img_server'];
								$img['img_url']	=$this->images[$image['img_new_id']]['img_url'];
								$img['root_id']			=$this->images[$image['img_new_id']]['root_id'];
								$img['time']			=$this->images[$image['img_new_id']]['time'];
								$img['user_id']			=$this->images[$image['img_new_id']]['user_id'];
								$img['user_name']		=$this->images[$image['img_new_id']]['user_name'];
								$img['item_id']			=$id;
								$img['position']		=$image['stt'];
								
								if($image['img_del_id'] && isset($this->images[$image['img_del_id']])){//Loại bỏ ảnh cũ
									if($this->images[$image['img_del_id']]['root_id'])
										$item_delete_ids.=($item_delete_ids?',':'').(int)$image['img_del_id'];
									else
										$unused_ids.=($unused_ids?',':'').(int)$image['img_del_id'];
								}
								if(!$img['root_id']){
									$img['root_id']=$image['img_new_id'];
								}
								$item_insert_images[$image['img_new_id']]=$img;
							}
														
						}
						else{
							$img_ids				   .=($img_ids?',':'').$image['img_new_id'];
							$img['title']				=addslashes($title);
							$img['item_id']				=$id;
							$img['img_server']			=$image['img_server'];
							$img['img_url']	='';
							$img['root_id']				=0;
							$img['time']				=TIME_NOW;
							$img['user_id']				=$this->item['user_id'];
							$img['user_name']			=$this->item['user_name'];
							$img['item_id']				=$id;
							$img['position']			=$image['stt'];
							if($image['img_del_id'] && isset($this->images[$image['img_del_id']])){//Loại bỏ ảnh cũ
								if($this->images[$image['img_del_id']]['root_id'])
									$item_delete_ids.=($item_delete_ids?',':'').(int)$image['img_del_id'];
								else
									$unused_ids.=($unused_ids?',':'').(int)$image['img_del_id'];
							}
							
							if(!isset($item_images[$image['img_new_id']])){	
								$item_images[$image['img_new_id']]=$img;
							}
							else{
								$img['root_id']=$image['img_new_id'];
								$item_insert_temp_images[$image['img_new_id']]=$img;//Đúp bản ghi trong trường hợp 1 ảnh được chọn tại nhiều vị trí
							}							
						}
					}
					elseif($image['id'] && $image['id'] == $_POST['image_deleted'][$image['stt']]){//Loại bỏ ảnh
						if($this->images[$image['id']]['root_id'])
							$item_delete_ids.=($item_delete_ids?',':'').(int)$image['id'];
						else
							$unused_ids.=($unused_ids?',':'').(int)$image['id'];
					}
					elseif ($image['id'] && $_POST['image_title'][$image['stt']]){
						$item_have_image =1;

						$title=($_POST['image_title'][$image['stt']]!='Ghi chú ảnh')?$_POST['image_title'][$image['stt']]:'';
						$title=str_replace(array('"'),array('&quot;'),stripslashes($title));
						$title=($title && !AZLib::checkBadWord($title))?$title:'';
						
						if($title!=$this->images[$image['id']]['title']){//Nếu Tên sản phẩm ảnh thay đổi thì cập nhật Tên sản phẩm cho ảnh!
							$this->images[$image['id']]['title']=addslashes($title);
							$item_update_images[$image['id']]	=$this->images[$image['id']];
						}
					}
					else{
						$item_have_image =1;
					}
				}
			}
			if($img_ids){
				//$re=DB::query('SELECT id, item_id, img_server, img_url, time FROM item_image WHERE id IN('.$img_ids.') AND user_id='.$this->item['user_id']);
				$re=DB::query('SELECT id, item_id, user_id, img_server, img_url, time FROM item_image WHERE id IN('.$img_ids.')');
				if($re){
					while ($img=mysql_fetch_assoc($re)){
						if($img['user_id'] == $this->item['user_id']){
							if(isset($item_insert_temp_images[$img['id']])){
								$item_insert_temp_images[$img['id']]['img_server']		=$img['img_server'];
								$item_insert_temp_images[$img['id']]['img_url']	=$img['img_url'];
								$item_insert_temp_images[$img['id']]['root_id']			=$img['id'];
								$item_insert_temp_images[$img['id']]['time']			=$img['time'];
								$item_insert_images[]=$item_insert_temp_images[$img['id']];
							}
							
							$item_images[$img['id']]['time']				=$img['time'];
							$item_images[$img['id']]['img_url']	=$img['img_url'];
							
							if($img['item_id']){//Đã có item_id rồi, đúp bản ghi
								$image=$item_images[$img['id']];
								
								if($img['root_id'])
									$image['root_id']=$img['root_id'];
								else 
									$image['root_id']=$img['id'];
								
								$item_insert_images[]=$image;
							}
							else{//Chưa có item_id, cập nhật
								$img['item_id']=$id;
								$item_update_images[$img['id']]=$item_images[$img['id']];
							}						
						}
					}
				}
			}	
			
			if($item_insert_images){
				$inser_sql='';
				foreach ($item_insert_images as $item_image){
					$inser_sql.=($inser_sql?",":"")."
						('".addslashes($item_image['title'])."',
						'".$item_image['position']."','".$item_image['item_id']."','".$item_image['img_server']."','".$item_image['img_url']."','".$item_image['root_id']."',
						'".$item_image['time']."','".$item_image['user_id']."','".$item_image['user_name']."')";
				}
				
				$inser_sql="INSERT INTO `item_image` (`title`,`position`,`item_id`,`img_server`,`img_url`,`root_id`,`time`,`user_id`,`user_name`) 
							VALUES ".$inser_sql;
				DB::query($inser_sql);
			}
			
			if($item_update_images){
				foreach ($item_update_images as $img_id=>$item_image){
					if(!DB::update('item_image',$item_image,'id='.$img_id)){
						$image_err=true;
					}
				}
			}
		
			//if($item_delete_ids && !DB::delete('item_image','id IN('.$item_delete_ids.') AND user_id='.$this->item['user_id'].' AND root_id!=0')){

			if($item_delete_ids && !DB::delete('item_image','id IN('.$item_delete_ids.') AND root_id!=0')){
				$image_err=true;
			}
			
			if($unused_ids && !DB::update('item_image',array('item_id'=>'0','title'=>'','position'=>'0'),'id IN('.$unused_ids.') AND user_id='.$this->item['user_id'].' AND root_id=0')){
				$image_err=true;
			}
			
			//$main_img = DB::select('item_image','item_id='.$id.' AND user_id='.$this->item['user_id'].' ORDER BY position ASC');
			$main_img = DB::select('item_image','item_id='.$id.' ORDER BY position ASC');
			
			if($main_img){
				$img_url	= $main_img['img_url'];
				$i_server 	= $main_img['img_server'];
			}
			else{
				$img_url	= '';
				$i_server 		= 0;
			}
			
			if($item_insert_images || $item_update_images || $item_delete_ids || $unused_ids){
				Item::get_item_images($id,1);
			}

			//tuannk 2010.07.26
			
			//end tuannk 2010.07.26
			
			/*if($this->img_url == '' && $img_url !='' )
			{
				DB::update('item',array( 'img_server'=>$i_server, 'img_url'=>$img_url,'have_image'=>1),'id='.$id);
			}
			elseif($item_have_image){
				DB::update('item',array( 'have_image'=>1),'id='.$id);
			}*/
			
			##############################################################################
			#Filters
			$filters = Url::get('filter');
			
			$filter_search 	= "";
			$filter_ids 	= "";
			
			foreach ($filters as $fgid => $fils)
			{
				foreach ($fils as $fid)
				{
					$filter_search 	.= ($filter_search != '' ? " ":'')	. "g{$fgid}f{$fid}f";
					
					$filter_ids 	.= ($filter_ids != '' ? ",":'')		. $fid;
				}
			}
			
			#Filters
			##############################################################################
			
			$item_array['filter_search'] 	= $filter_search;
			$item_array['filter_ids'] 		= $filter_ids;
			
			
			if($this->img_url == '' && $img_url !='' )
			{
				$item_array['img_server'] 	= $i_server;
				$item_array['img_url'] 		= $img_url;
				$item_array['have_image'] 	= 1;
			}
			elseif($item_have_image){
				$item_array['have_image'] 	= 1;
			}
			
			//DB::update('item',array( 'have_image'=>1),'id='.$id);
			
			DB::update('item',$item_array,'id='.$id);

			if(MEMCACHE_ON){
				AZMemcache::do_remove("item:$id");
			}
			
			if(Url::get('ref'))
				Url::redirect("manage_item");
			else
				Url::redirect("item_detail",array("id"=>$id));
		}
	}
}
?>